const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 生成随机整数，包含最小值和最大值
 */
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 生成过去days天内的随机日期
 */
function getRandomDate(days) {
  const date = new Date();
  date.setDate(date.getDate() - getRandomInt(0, days));
  date.setHours(getRandomInt(9, 22), getRandomInt(0, 59), getRandomInt(0, 59));
  return date;
}

/**
 * 生成测试订单数据
 */
async function seedTestOrders() {
  try {
    console.log('开始生成测试订单数据...');

    // 获取所有渠道
    const channels = await prisma.channel.findMany();
    if (channels.length === 0) {
      console.error('未找到任何渠道，请先运行渠道种子脚本');
      return;
    }

    // 获取所有产品
    const products = await prisma.product.findMany({
      where: { status: true }
    });
    if (products.length === 0) {
      console.error('未找到任何产品，请先运行产品种子脚本');
      return;
    }

    // 获取支付方式
    const paymentMethods = await prisma.paymentMethod.findMany();
    if (paymentMethods.length === 0) {
      console.error('未找到任何支付方式，请先运行支付方式种子脚本');
      return;
    }

    // 获取一个用户作为测试订单的用户
    const users = await prisma.user.findMany();
    if (users.length === 0) {
      console.error('未找到任何用户，请先运行用户种子脚本');
      return;
    }
    const testUser = users[0];

    // 生成每个渠道的订单数据
    const orderPromises = [];
    const orderCount = {
      total: 0
    };

    // 为每个渠道设置不同的订单数量，模拟渠道差异
    channels.forEach(channel => {
      // 线下渠道订单最多，然后是外卖平台，再是电商平台
      let orderNum = 5; // 基础订单数
      
      if (channel.name.includes('线下')) {
        orderNum = 20; // 线下订单多一些
      } else if (channel.name.includes('美团') || channel.name.includes('饿了么')) {
        orderNum = 15; // 外卖平台次之
      } else if (channel.name.includes('小程序')) {
        orderNum = 10; // 小程序再次之
      }
      
      orderCount[channel.name] = orderNum;
      orderCount.total += orderNum;
    });

    console.log(`计划为${channels.length}个渠道创建共${orderCount.total}个测试订单`);

    // 为每个渠道创建订单
    for (const channel of channels) {
      const orderNum = orderCount[channel.name];
      
      for (let i = 0; i < orderNum; i++) {
        // 随机选择1-5个产品
        const orderProductCount = getRandomInt(1, 5);
        const orderItems = [];
        const selectedProducts = new Set();
        
        // 随机生成订单项
        let subtotal = 0;
        for (let j = 0; j < orderProductCount; j++) {
          let productIndex;
          // 确保不重复选择同一个产品
          do {
            productIndex = getRandomInt(0, products.length - 1);
          } while (selectedProducts.has(productIndex));
          
          selectedProducts.add(productIndex);
          const product = products[productIndex];
          
          // 随机生成购买数量
          const quantity = getRandomInt(1, 3);
          
          // 根据渠道设置价格（线下渠道使用产品原价，其他渠道可能有溢价）
          let price = product.price;
          if (channel.name.includes('美团') || channel.name.includes('饿了么')) {
            price = parseFloat((price * 1.1).toFixed(2)); // 外卖平台加价10%
          } else if (!channel.name.includes('线下')) {
            price = parseFloat((price * 1.05).toFixed(2)); // 其他电商平台加价5%
          }
          
          const itemTotal = price * quantity;
          subtotal += itemTotal;
          
          orderItems.push({
            productId: product.id,
            quantity: quantity,
            price: price
          });
        }
        
        // 计算订单总金额（有时添加随机折扣）
        let discount = 0;
        if (getRandomInt(1, 10) <= 3) { // 30%概率有折扣
          discount = parseFloat((subtotal * getRandomInt(5, 20) / 100).toFixed(2));
        }
        
        const totalAmount = parseFloat((subtotal - discount).toFixed(2));
        
        // 随机选择支付方式
        const paymentMethod = paymentMethods[getRandomInt(0, paymentMethods.length - 1)].id;
        
        // 随机生成订单创建时间（最近30天内）
        const createdAt = getRandomDate(30);
        
        // 生成订单编号 (格式: 年月日+四位随机数)
        const generateOrderNo = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
          return `${year}${month}${day}${random}`;
        };
        
        const orderNo = generateOrderNo(createdAt);
        
        // 创建订单对象
        const orderData = {
          orderNo: orderNo,
          userId: testUser.id,
          channelId: channel.id,
          total: totalAmount,
          status: 'completed', // 所有订单都是已完成状态
          createdAt: createdAt,
          updatedAt: createdAt,
          items: {
            create: orderItems
          },
          payments: {
            create: [
              {
                method: paymentMethod,
                amount: totalAmount,
                status: 'completed',
                createdAt: createdAt,
                updatedAt: createdAt
              }
            ]
          }
        };
        
        // 添加到批量创建队列
        orderPromises.push(prisma.order.create({
          data: orderData,
          include: { items: true, payments: true }
        }));
      }
    }
    
    // 批量创建订单
    const createdOrders = await Promise.all(orderPromises);
    
    console.log(`成功创建${createdOrders.length}个测试订单`);
    
    // 统计各渠道订单金额
    const channelStats = {};
    for (const order of createdOrders) {
      const channelId = order.channelId;
      const channel = channels.find(c => c.id === channelId);
      
      if (!channelStats[channel.name]) {
        channelStats[channel.name] = {
          count: 0,
          amount: 0
        };
      }
      
      channelStats[channel.name].count++;
      channelStats[channel.name].amount += parseFloat(order.total);
    }
    
    console.log('各渠道订单统计:');
    for (const [channelName, stats] of Object.entries(channelStats)) {
      console.log(`- ${channelName}: ${stats.count}个订单, 总金额: ¥${stats.amount.toFixed(2)}`);
    }
    
  } catch (error) {
    console.error('生成测试订单数据时出错:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// 执行函数
seedTestOrders(); 